/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			langsupport.cc
  \date			Jul 2011
  \author		TNick

  \brief		Contains the implementation for LangSupport class


  Copyright (c) 2011, Nicu Tofan
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright holder nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL NICU TOFAN BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

/* this is expected to define APP_NAME and LANG_FILES_CACHE_COUNT */
#include	<main.h>

#include	<QDebug>
#include	<QString>
#include	<QSettings>
#include	<QDir>
#include	<QAction>
#include	<QMenu>
#include	<QDesktopServices>
#include	<QTranslator>
#include	<QFileDialog>
#include	<QApplication>
#include	<QMessageBox>

#include	"langsupport.h"

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */

QString			LangSupport::s_from_stg;



/* ------------------------------------------------------------------------- */
void		LangSupport::appStart			(void)
{
#ifndef QT_NO_TRANSLATION

	/* get the path to language directory */
	QString lang_dir =
			QDesktopServices::storageLocation(
				QDesktopServices::DataLocation) +
            QString("lang/");

	/* read the settings; if none is found, default to current locale */
	QSettings settings;
	settings.beginGroup("language");
	s_from_stg =
			settings.value(
				"lang_file",
                lang_dir + QString(APP_NAME  "_") +
				QLocale::system().name() +
				QString(".qm")
				).toString();
	settings.endGroup();


	/* an empty string signals using default (english) */
	if (s_from_stg.isEmpty())
		{
			qDebug() << "LANG: Using build-in language.";
			return;
		}

	/* attempt to load the file */
	QTranslator translator;
	if (!translator.load(s_from_stg))
		{
			qDebug() << "LANG: Failed to load file saved in settings: "
					 << s_from_stg;
			s_from_stg.clear();

            settings.beginGroup("language");
            settings.setValue(
                        "lang_file",
                        QString());
            settings.endGroup();
            return;
		}

	/* finally, install this translator */
	qApp->installTranslator(&translator);

	qDebug() << "LANG: Language file " << s_from_stg << "was loaded";
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		LangSupport::populateMenu		(QMenu * to_manage)
{
#ifndef QT_NO_TRANSLATION

	QAction * new_act;
	QString full_path;
	QString id_portion;
	QStringList file_lst_base;
	QStringList file_lst;

	/* cancel the language change */
    if (s_from_stg.isEmpty())
        {
            id_portion = QString("english");
        }
    else
        {
            QFileInfo	f_inf(s_from_stg);
            if (f_inf.exists())
                {
                    id_portion = f_inf.baseName();
                    if (id_portion.startsWith(QString(APP_NAME)))
                        {
                            id_portion = id_portion.right(
                                        id_portion.length() -
                                        (sizeof(APP_NAME) - 1));
                        }
                }
            else
                id_portion = QString("english");
        }
    new_act = new QAction(
                QObject::tr("Current language (%1)").arg(id_portion),
                to_manage);
    new_act->setToolTip(
                QObject::tr(
                    "Revert any changes to language "
                    "to be loaded after restart"));
    new_act->setCheckable(true);
    new_act->setChecked(true);
    new_act->setData(QVariant(USE_CURRENT));
    to_manage->addAction(new_act);


    /* load a file */
    new_act = new QAction(QObject::tr("Load language..."), to_manage);
    new_act->setToolTip(
                QObject::tr(
                    "Allows the user to select a language file."));
    to_manage->addAction(new_act);

    to_manage->addSeparator();

    /* add default */
    new_act = new QAction(
                QString("english"),
                to_manage);
    new_act->setToolTip(QObject::tr("Default language"));
    new_act->setCheckable(true);
    new_act->setData(QVariant(USE_DEFAULT));
    to_manage->addAction(new_act);


    /* find files in standard location */
    QDir dir;
    dir.setFilter(QDir::Files | QDir::Readable | QDir::NoSymLinks);
    dir.setSorting(QDir::Name);
    dir.setNameFilters(QStringList() << APP_NAME "_*.qm");
    dir.setPath(QDesktopServices::storageLocation(
                    QDesktopServices::DataLocation) +
                QString("/lang"));
    if (dir.exists())
        {

            file_lst = dir.entryList();
            if (file_lst.count() > 0)
                {
                    foreach (QString s_file_name, file_lst)			{
                        full_path = dir.path() + "/" + s_file_name;
                        id_portion = s_file_name.mid(
                                    sizeof(APP_NAME "_")-1,
                                    s_file_name.length() - (
                                        sizeof(APP_NAME "_.qm")-1)
                                    );

                        /* add a file */
                        new_act = new QAction(
                                    id_portion,
                                    to_manage);
                        new_act->setToolTip(full_path);
                        new_act->setCheckable(true);
                        new_act->setData(QVariant(IN_DEF_LOC));
                        to_manage->addAction(new_act);
                        file_lst_base << full_path;
                    }
                }
        }
    else
        {
            dir.mkpath(dir.path());
        }


    /* get recent language files */
    QSettings settings;
    settings.beginGroup("language");

    file_lst.clear();
    int i = 0;
    for (i = 0; i < LANG_FILES_CACHE_COUNT; i++)
        {
            full_path =
                    settings.value(
                        QString("recent_lang_file_%1").arg(i),
                        QString()
                        ).toString();
            if (full_path.isEmpty())
                break;
            file_lst.append(full_path);
        }
    if (i != 0)
        {
            to_manage->addSeparator();
            foreach	(full_path, file_lst)
                {
                    QFileInfo	f_inf(full_path);
                    if (f_inf.exists())
                        {
                            if (file_lst_base.indexOf(full_path) != -1)
                                continue;

                            id_portion = f_inf.baseName();
                            if (id_portion.startsWith(QString(APP_NAME)))
                                {
                                    id_portion = id_portion.right(
                                                id_portion.length() -
                                                (sizeof(APP_NAME) - 1));
                                }

                            /* add a file */
                            new_act = new QAction(
                                        id_portion,
                                        to_manage);
                            new_act->setToolTip(full_path);
                            new_act->setData(QVariant(RECENT_LOADED));
                            new_act->setCheckable(true);
                            to_manage->addAction(new_act);
                        }
                }
        }

    settings.endGroup();

    /* the owner shall connect */

#else
	to_manage->addAction(tr("(build without support for translations"));
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		LangSupport::menuHandler		(
	QMenu * to_manage, QAction * act_tigg)
{
#ifndef QT_NO_TRANSLATION

	QList<QAction*> lst_act = to_manage->actions();
	int i;
	int j;
	QAction *		new_act;

	switch	(act_tigg->data().toInt())	{
	case	LOAD_A_FILE:		{

        QFileDialog::Options options;
        QString selectedFilter;
        QString fileName = QFileDialog::getOpenFileName(
                    qApp->activeWindow(),
                    QObject::tr("Select language file to load..."),
                    QString(),
                    QObject::tr("All Files (*);;Language files (*.qm)"),
                    &selectedFilter,
                    options);
        if (!fileName.isEmpty())
            {
#ifdef	LANG_CHECK_ON_LOAD
                QTranslator translator;
                if (!translator.load(fileName))
                    {
                        QMessageBox::critical(
                                    qApp->activeWindow(),
                                    QString(QObject::tr("Language file error")),
                                    QString(QObject::tr("Error while reading language\n"
                                                        "file. Please check that the file\n"
                                                        "exists, may be read and has\n"
                                                        "appropriate format.")));
                        return;
                    }
#endif
                /* iterate in all menus; check for existance; find stuff */
                i = -1;
                j = 0;
                int first_custom = -1;
                int count_custom = 0;
                foreach(QAction * itr_act, lst_act)		{
                    if (itr_act->toolTip() == fileName)
                        {
                            itr_act->setChecked(true);
                            i = j;
                        }
                    else
                        {
                            itr_act->setChecked(false);
                        }
                    if (itr_act->data().toInt() == RECENT_LOADED)
                        {
                            if(first_custom == -1)
                                {
                                    first_custom = j;
                                    count_custom = 1;
                                }
                            else
                                count_custom++;
                        }
                    j++;
                }
                if (i != 0)
                    { /* already loaded */
                        return;
                    }

                QString		id_portion;
                QFileInfo	f_inf(fileName);
                id_portion = f_inf.baseName();
                if (id_portion.startsWith(QString(APP_NAME)))
                    {
                        id_portion = id_portion.right(
                                    id_portion.length() -
                                    (sizeof(APP_NAME) - 1));
                    }

                /* add a file */
                new_act = new QAction(
                            id_portion,
                            to_manage);
                new_act->setToolTip(fileName);
                new_act->setData(QVariant(RECENT_LOADED));
                new_act->setCheckable(true);

                if (first_custom == -1)
                    {
                        to_manage->addSeparator();
                        to_manage->addAction(new_act);
                    }
                else
                    {
                        to_manage->insertAction(lst_act[first_custom], new_act);
                        if (count_custom >= LANG_FILES_CACHE_COUNT)
                            {
                                to_manage->removeAction(lst_act.last());
                            }
                    }
            }

        break;}
    case	USE_CURRENT:        {
        foreach(QAction * itr_act, lst_act)		{
            itr_act->setChecked(false);
        }
        act_tigg->setChecked(true);
        break;}
    case	USE_DEFAULT:
	case	IN_DEF_LOC:
	case	RECENT_LOADED:		{
        foreach(QAction * itr_act, lst_act)		{
            itr_act->setChecked(false);
        }
        act_tigg->setChecked(true);

        QMessageBox::information(
                    qApp->activeWindow(),
                    QString(QObject::tr("Language changed")),
                    QString(QObject::tr("Your request to change the language\n"
                                        "was noted but can not be fulfilled\n"
                                        "until the application is restarted.")));

        break;}
	}


#else
	Q_UNUSED(to_manage);
	Q_UNUSED(act_tigg);
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		LangSupport::saveOptions		(QMenu * to_manage)
{
#ifndef QT_NO_TRANSLATION

	QList<QAction*> lst_act = to_manage->actions();

	int i;
	int j;
	int first_custom = -1;
	int count_custom = 0;

	i = -1;
	j = 0;
	foreach(QAction * itr_act, lst_act)		{
		if (itr_act->isChecked())
			{
				i = j;
			}
		if (itr_act->data().toInt() == RECENT_LOADED)
			{
				if(first_custom == -1)
					{
						first_custom = j;
						count_custom = 1;
					}
				else
					count_custom++;
			}
		j++;
	}

	QSettings settings;
	settings.beginGroup("language");

    /* if there is a change (-1 = not found, 0 - keep current) */
    if (i > 0)
		{
            switch (lst_act[i]->data().toInt()) {
            case    IN_DEF_LOC:
            case    RECENT_LOADED:  {
                settings.setValue(
                            "lang_file",
                            lst_act[i]->toolTip()
                            );
                break; }
            case    USE_CURRENT:    {
                break; }
            default:                { /* case	USE_DEFAULT, LOAD_A_FILE */
                settings.setValue(
                            "lang_file",
                            QString()
                            );
                break; }
            }
		}

    if (first_custom != -1)
        {
            for (i = first_custom;  i < lst_act.count(); i++)
                {
                    settings.setValue(
                                QString("recent_lang_file_%1").arg(i-first_custom).toAscii(),
                                lst_act[i]->toolTip()
                                );
                }
        }
    else
        {
            i = 0;
        }
	settings.setValue(
                QString("recent_lang_file_%1").arg(i).toAscii(),
				QString()
				);

	settings.endGroup();
#else
	Q_UNUSED(to_manage);
#endif

}
/* ========================================================================= */

/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
